<template>
    <view class="page">
        <view class="tip-wrap">
            <view class="tip-icon"></view>
            <view class="text">新手机号验证后，即可绑定成功！</view>
        </view>
        <view class="input-wrap">
            <input 
                type="number" 
                placeholder="手机号" 
                class="cellphone" 
                v-model="cellphone" 
                maxlength="11"
            />
        </view>
        <view class="input-wrap">
            <view class="msg-code">
                <input 
                    type="number" 
                    placeholder="请输入短信验证码" 
                    v-model="msgCode" 
                    maxlength="6"
                />
            </view>
            <view 
                :class="['msg-code-btn', { active: isSendCode }]" 
                @click="getMsgCode"
            >
                {{msgText}}
            </view>
        </view>
        <button type="button" class="submit-btn" @click="submit">确认绑定</button>
    </view>
</template>

<script>
    import {mapActions} from "vuex";
    export default {
        name: "bind-cellphone",
        data(){
            return {
                branch_shop_id: "",
                table_code: "",
                cellphone: "", // 手机号
                msgCode: "", // 短信验证码
                msgText: "获取验证码",
                isSendCode: true, // 是否可以发送验证码
                countdown: 60, // 倒计时秒数
                isSubmit: true, // 是否可以提交
                timer: null // 计时器
            }
        },
        onLoad(opts){
            this.branch_shop_id = opts.branch_shop_id || "";
            this.table_code = opts.table_code || "";
            this.$utils.safeUser(this, this.branch_shop_id, this.table_code);
        },
        onUnload() {
            // 离开页面时清除定时器
            clearInterval(this.timer);
        },
        methods:{
            ...mapActions({
                existCellphone: "user/existCellphone", // 是否存在手机号
                sendCode: "vcode/sendCode", // 发送短信验证码
                bindCellhone: "user/bindCellhone" // 绑定手机号
            }),
            
            // 验证手机号格式
            validatePhone() {
                if (!this.cellphone) {
                    uni.showToast({ title: "请输入手机号", icon: "none" });
                    return false;
                }
                if (!/^1[3-9]\d{9}$/.test(this.cellphone)) {
                    uni.showToast({ title: "手机号格式不正确", icon: "none" });
                    return false;
                }
                return true;
            },
            
            // 获取短信验证码
            async getMsgCode() {
                if (!this.isSendCode) return;
                if (!this.validatePhone()) return;
                
                try {
                    // 检查手机号是否已存在
                    const existRes = await this.existCellphone({ 
                        cellphone: this.cellphone 
                    });
                    
                    if (existRes.data.exist === 1) {
                        uni.showToast({ title: "手机号已存在", icon: "none" });
                        return;
                    }
                    
                    // 发送验证码
                    const codeRes = await this.sendCode({ 
                        cellphone: this.cellphone 
                    });
                    
                    if (codeRes.code === 200) {
                        uni.showToast({ title: "验证码已发送", icon: "success" });
                        this.startCountdown();
                    } else {
                        uni.showToast({ title: codeRes.data || "发送失败", icon: "none" });
                    }
                } catch (error) {
                    console.error("发送验证码失败:", error);
                    uni.showToast({ title: "发送失败，请重试", icon: "none" });
                }
            },
            
            // 开始倒计时
            startCountdown() {
                this.isSendCode = false;
                this.msgText = `${this.countdown}秒后重发`;
                
                this.timer = setInterval(() => {
                    if (this.countdown <= 0) {
                        clearInterval(this.timer);
                        this.isSendCode = true;
                        this.countdown = 60;
                        this.msgText = "获取验证码";
                    } else {
                        this.countdown--;
                        this.msgText = `${this.countdown}秒后重发`;
                    }
                }, 1000);
            },
            
            // 绑定手机号
            async submit() {
                if (!this.isSubmit) return;
                if (!this.validatePhone()) return;
                
                if (!this.msgCode) {
                    uni.showToast({ title: "请输入验证码", icon: "none" });
                    return;
                }
                
                this.isSubmit = false;
                
                try {
                    // 检查手机号是否已存在
                    const existRes = await this.existCellphone({ 
                        cellphone: this.cellphone 
                    });
                    
                    if (existRes.data.exist === 1) {
                        uni.showToast({ title: "手机号已存在", icon: "none" });
                        this.isSubmit = true;
                        return;
                    }
                    
                    // 绑定手机号
                    const bindRes = await this.bindCellhone({
                        cellphone: this.cellphone,
                        sms_code: this.msgCode
                    });
                    
                    if (bindRes.code === 200) {
                        uni.showToast({ title: "绑定成功", icon: "success" });
                        setTimeout(() => uni.navigateBack(), 1500);
                    } else {
                        uni.showToast({ title: bindRes.data || "绑定失败", icon: "none" });
                        this.isSubmit = true;
                    }
                } catch (error) {
                    console.error("绑定失败:", error);
                    uni.showToast({ title: "绑定失败，请重试", icon: "none" });
                    this.isSubmit = true;
                }
            }
        }
    }
</script>

<style scoped>
    .page{width:100%;min-height:100vh;overflow:hidden;background-color:#FFFFFF;}
    .tip-wrap{width:100%;height:100rpx;background-color:#f3f5c4;display:flex;box-sizing: border-box;align-items: center;padding-left:40rpx;margin-bottom:40rpx;}
    .tip-wrap .tip-icon{width:40rpx;height:40rpx;background-image:url("~@/static/images/user/tip.png");background-size:100%;background-position: center;background-repeat: no-repeat;margin-right:20rpx;}
    .tip-wrap .text{font-size:28rpx;color:#ac7700;}

    .input-wrap{width:90%;height:80rpx;background-color:#FFFFFF;border:1px solid #EFEFEF;margin:0 auto;display:flex;align-items: center;box-sizing: border-box;padding-left:20rpx;border-radius: 5px;margin-bottom:20rpx;}
    .input-wrap .cellphone{width:90%;height:80%;font-size:28rpx;}

    .input-wrap .msg-code{width:70%;height:100%;border-right: 1px solid #EFEFEF}
    .input-wrap .msg-code input{width:100%;height:100%;font-size:28rpx;}

    .input-wrap .msg-code-btn{width:29%;height:100%;text-align:center;line-height:80rpx;font-size:28rpx;color:#717376;}
    .input-wrap .msg-code-btn.active{color:#E30019}

    .input-wrap .msg-code-btn image{width:80%;height:80%;margin-top:9rpx;}

    .submit-btn{width:200rpx;height:60rpx;margin:0 auto;background-color:#E30019;color:#FFFFFF;font-size:28rpx;margin-top:40rpx;line-height:60rpx;border-radius: 4px;}
</style>